package com.makemoney.miniprogram.modules.users.dto;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.makemoney.miniprogram.modules.users.entity.Roles;
import com.makemoney.miniprogram.modules.users.entity.Users;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class MyUserDetails implements IMyUserDetails {
    private final Users user;
    private final List<Roles> roles;

    @JsonCreator
    public MyUserDetails(@JsonProperty("user") Users user, @JsonProperty("roles") List<Roles> roles) {
        this.user = user;
        this.roles = roles;
    }

    @Override
    public Users getUser() {
        return this.user;
    }
    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles.stream()
                .map(r -> new SimpleGrantedAuthority(r.getRoleKey()))
                .collect(Collectors.toList());
    }
    @JsonIgnore
    @Override
    public String getPassword() {
        return user.getPassword();
    }
    @JsonIgnore
    @Override
    public String getUsername() {
        return user.getUserName();
    }

    /**
     * 账户是否未过期
     *
     * @return true 表示未过期
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账户是否未锁定
     *
     * @return true 表示未锁定
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return user.getLocked().equals(0);
    }

    /**
     * 凭证（密码）是否未过期
     *
     * @return true 表示未过期
     */
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 账户是否启用
     *
     * @return true 表示启用
     */
    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return this.isAccountNonLocked();
    }
}
